﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using RiskMan.DataClass.Models;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.Ledder
{
    /// <summary>
    /// Логика взаимодействия для newLedder.xaml
    /// </summary>
    public partial class newLedder : Window
    {
        private DataClass.Models.NotBasModels.LedderItem ldItem;
        private DataClass.Data data;
        List<Trade> trades;

        public newLedder()
        {
            InitializeComponent();
        }


        public newLedder(DataClass.Models.NotBasModels.LedderItem ldItem, DataClass.Data data, bool isedit)
        {
            InitializeComponent();

            this.ldItem = ldItem;
            this.data = data;

            trades = data.GetTradeList();

            ComboBox_ClientCode.ItemsSource = trades.Select(a => a.ClientCode).ToList();
            for (int i = 0; i < ComboBox_ClientCode.Items.Count; i++)
            {
                if (ComboBox_ClientCode.Items[i].ToString() == ldItem.ClientCode)
                    ComboBox_ClientCode.SelectedIndex = i;
            }
            cmbxOperation.ItemsSource = new List<string>() { "Купля", "Продажа" };
            cmbxOperation.SelectedIndex = 0;

            cmbxOperation.SelectedValue = ldItem.Operation;



            #region Seccode
            cmbxInstrument.ItemsSource = data.GetSeccodeList();
            for (int i = 0; i < cmbxInstrument.Items.Count; i++)
            {
                if (cmbxInstrument.Items[i].ToString() == ldItem.Instrument)
                    cmbxInstrument.SelectedIndex = i;
            }
            #endregion

           

            txbxMaxOpenPrice.Text = ldItem.Maxprice.ToString();
            txbxProfit.Text = ldItem.Profit.ToString();
            txbxQuantity.Text = ldItem.Quantity.ToString();
            txbxStep.Text = ldItem.Step.ToString();
            txbxSumOpenOrderActive.Text = ldItem.SumOrders.ToString();
            if (ldItem.DeepOrders <= 0)
                ldItem.DeepOrders = Properties.Settings.Default.DeepOrders;

            txbxDeep.Text = ldItem.DeepOrders.ToString();
            txbxSumOrdersProfit.Text = ldItem.SumOrdersProfit.ToString();

            if (ldItem.StaticsticItem == null)
                ldItem.StaticsticItem = new DataClass.Models.NotBasModels.Statistics();
        }

        private void Button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Accept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ComboBox_ClientCode.SelectedIndex >= 0)
                {
                    ldItem.ClientCode = ComboBox_ClientCode.SelectedValue.ToString();
                    List<Trade> trades = data.GetTradeList();

                    for (int i = 0; i < trades.Count; i++)
                        if (trades[i].ClientCode == ldItem.ClientCode)
                            ldItem.Account = trades[i].Account;
                }
                else
                {
                    new DialogOkCancel("Выберите код клиента(счет)!", "Ошибка добавления");
                    return;
                }

                if (cmbxOperation.SelectedIndex >= 0)
                    ldItem.Operation = cmbxOperation.SelectedValue.ToString();
                else
                {
                    new DialogOkCancel("Выберите вид операции!", "Ошибка добавления");
                    return;
                }

                if (cmbxInstrument.SelectedIndex >= 0)
                    if (cmbxInstrument.SelectedValue.ToString() != "Не выбран")
                        ldItem.Instrument = cmbxInstrument.SelectedValue.ToString();
                    else
                    {
                        new DialogOkCancel("Выберите торгуемый инструмент!", "Ошибка добавления");
                        return;
                    }
                else
                {
                    new DialogOkCancel("Выберите торгуемый инструмент!", "Ошибка добавления");
                    return;
                }

                ldItem.Maxprice = Convert.ToDouble(txbxMaxOpenPrice.Text);
                ldItem.Profit = Convert.ToDouble(txbxProfit.Text);
                ldItem.Quantity = Convert.ToInt32(txbxQuantity.Text);
                ldItem.Step = Convert.ToDouble(txbxStep.Text);
                ldItem.SumOrders = Convert.ToInt32(txbxSumOpenOrderActive.Text);
                ldItem.DeepOrders = Convert.ToInt32(txbxDeep.Text);
                ldItem.SumOrdersProfit = Convert.ToInt32(txbxSumOrdersProfit.Text);
                if (ldItem.Maxprice <= 0 || ldItem.Profit <= 0 || ldItem.Quantity <= 0 || ldItem.Step <= 0
                    || ldItem.SumOrders <= 0 || ldItem.DeepOrders <= 0 || ldItem.SumOrdersProfit<=0)
                {
                    new DialogOkCancel("Параметр не может равнятся нулю!", "Ошибка добавления");
                    return;
                }

                ldItem.GuidLedder = Guid.NewGuid();

                this.Close();
            }
            catch
            { }

        }

        private void ComboBox_ClientCode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //for (int i = 0; i < trades.Count; i++)
            //{
            //    if (ComboBox_ClientCode.SelectedIndex >= 0)
            //    {
            //        if (trades[i].ClientCode == ComboBox_ClientCode.SelectedItem.ToString())
            //        {
            //            //if (trades[i].Account == trades[i].ClientCode)
            //            //{
            //            //    ComboBox_Modes.IsEnabled = true;
            //            //    ComboBox_Modes.SelectedIndex = 0;
            //            //}
            //            //else
            //            //{
            //            //    ComboBox_Modes.IsEnabled = false;
            //            //    ComboBox_Modes.SelectedIndex = 3;
            //            ComboBox_ClientCode.SelectedIndex = i;
            //            //}
            //        }
            //    }
            //}
        }

        private void txbxMaxOpenPrice_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {

            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;

            if ((e.Text.IndexOf('.') == 0 || e.Text.IndexOf(',') == 0) && ((TextBox)sender).Text.IndexOf('.') == -1 && ((TextBox)sender).Text.IndexOf(',') == -1)
                e.Handled = false;
        }

        private void txbxMaxOpenPrice_TextChanged(object sender, TextChangedEventArgs e)
        {
            ((TextBox)sender).Text = ((TextBox)sender).Text.Replace('.', ',');
            ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
        }

        private void txbxDeep_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;
        }

        private void txbxMaxOpenPrice_GotFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                if (Convert.ToDouble(((TextBox)sender).Text) == 0)
                {
                    ((TextBox)sender).Text = "";
                }
        }

        private void txbx_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                ((TextBox)sender).Text = 0.ToString();
        }
    }
}
